import LanguageMng from "../../Managers/LanguageMng";

cc.Class({
    extends: cc.Component,

    properties: {
        headParent:{
            default:null,
            type:cc.Node
        },

        faceSprite:{
            default:null,
            type:cc.Sprite
        },

        nameEb:{
            default:null,
            type:cc.EditBox
        },

        labelCashLocal:{
            default:null,
            type:cc.Label
        },

        labelCashReal:{
            default:null,
            type:cc.Label
        },

        labelCashTotal:{
            default:null,
            type:cc.Label
        },

        faceBorder:{
            default:null,
            type:cc.Node
        },

        coinIcon1:{
            default:null,
            type:cc.Node
        },

        coinIcon2:{
            default:null,
            type:cc.Node
        },
        coinIcon3:{
            default:null,
            type:cc.Node
        },
    },

    // LIFE-CYCLE CALLBACKS:

    onLoad () {
        let faces = this.headParent.children
        for(let i=0;i<faces.length;i++){
            let node = faces[i]
            let btn = node.addComponent(cc.Button)
            btn.target = node

            cc.gg.baseUtil.addClickEventToNode(
                node,
                this.node,
                "UserConfig",
                "onFaceClicked")
        }

        this.netReqCount = 0
        this.completCount = 0

        this.faceBorder.position = cc.Vec2.ZERO
        this.faceBorder.active = false

        this._handleRefreshFace = this._onConfigRefreshFace.bind(this)
        cc.find("Canvas").on("config_refresh_face",this._handleRefreshFace,this)

        this.coinIcon1.active = !cc.gg.gameDataUtil.showRupee
        this.coinIcon2.active = !cc.gg.gameDataUtil.showRupee
        this.coinIcon3.active = !cc.gg.gameDataUtil.showRupee
    },

    onDestroy(){
        cc.find("Canvas").off(this._handleRefreshFace,this)
    },

    start () {
        cc.gg.tdUtil.doSendTdEvent("show_userconfig","")
    },

    _onConfigRefreshFace:function () {
        cc.log("更新UserConfig界面的face")
        cc.find("Canvas").emit("refresh_player_info")

        cc.gg.httpUtil.httpGet('/user/profile/get',null,function (result) {
            if(!result.succ){
                cc.gg.httpUtil.setUserToken(null)
                cc.gg.gameDataUtil.goToLogin(true)
            }else {
                result.data.face_bg = Math.random()*1000000
                cc.gg.dataMgr.setPlayerInfo(result.data)
                cc.logfl("get user info success:",result.data)

                let info = cc.gg.dataMgr.getPlayerInfo()
                cc.gg.logicUtil.initHead(info.img,this.faceSprite)
            }
        }.bind(this))
    },

    // update (dt) {},

    initUserConfig:function (lobbyUIMgr) {
        this.uiMgr = lobbyUIMgr
        let info = cc.gg.dataMgr.getPlayerInfo()
        let faceNum = cc.gg.logicUtil.initHead(info.img,this.faceSprite)
        if(!faceNum){
            this.hideBorder()
        }else {
            let faces = this.headParent.children
            for(let i=0;i<faces.length;i++){
                let node = faces[i]

                let startIdx = node.name.indexOf("_face") + 5
                let num = node.name.substr(startIdx)
                num = parseInt(num)
                if(num === faceNum){
                    this._showBorderOnNode(node)
                    break
                }
            }
        }

        this.labelCashLocal.string = cc.gg.gameDataUtil.getStringOfRupee(info.deposit)
        this.labelCashReal.string = cc.gg.gameDataUtil.getStringOfRupee(info.winnings)
        this.labelCashTotal.string = cc.gg.gameDataUtil.getStringOfRupee(info.deposit + info.winnings)
        this.nameEb.string = info.name
    },

    onFaceClicked:function (event) {
        let btnName = event.target.name
        let faces = this.headParent.children
        for(let i=0;i<faces.length;i++){
            let node = faces[i]
            if(node === event.target){
                if(!this.faceChanged) this.faceChanged = true
                this._showBorderOnNode(node)

                let startIdx = node.name.indexOf("_face") + 5
                let num = node.name.substr(startIdx)
                num = parseInt(num)
                cc.loader.loadRes("faces/user_config_face"+num,cc.SpriteFrame,function (err, frame) {
                    this.faceSprite.spriteFrame = frame
                }.bind(this))

                this.selectedFaceId = num
            }
        }
    },

    _showBorderOnNode:function (node) {
        if(!this.faceBorder.active) this.faceBorder.active = true
        this.faceBorder.parent = node
        // let worldPos = node.parent.convertToWorldSpaceAR(node.position)
        // this.faceBorder.position = this.faceBorder.parent.convertToNodeSpaceAR(worldPos)
    },

    hideBorder:function () {
        this.faceBorder.active = false
    },

    onCameraClicked:function (event) {
        cc.gg.baseUtil.openGalary('https://api.khelochalo.com:20040/img/upload',2,cc.gg.httpUtil.USER_TOKEN)
    },

    onUserConfigCloseClicked:function (event) {
        this.node.destroy()
    },

    onNameEbChanged:function (event) {
        if(!this.nameEbChanged) this.nameEbChanged = true
    },

    onSubmitClicked:function (event) {
        let changed = false
        if(this.nameEbChanged){
            changed = true
            this.netReqCount ++
            this.updateNameToServer()
        }

        if(this.faceChanged){
            changed = true
            this.netReqCount ++
            this.updateFaceToServer()
        }

        if(changed){
            cc.gg.toastMgr.showNetWaitting()
        }else
            this.checkNetFinish()
    },

    updateNameToServer:function () {
        cc.log("改名为：",this.nameEb.string)
        cc.gg.httpUtil.httpPost("/user/profile/name/update",{name:this.nameEb.string},function (result) {
            if (!result.succ) {
                cc.gg.toastMgr.showToast(LanguageMng.getSentence(151))
                return
            }

            this.completCount++
            cc.gg.dataMgr.getPlayerInfo().name = this.nameEb.string
            this.checkNetFinish()
        }.bind(this))
    },

    updateFaceToServer:function () {
        cc.log("头像变为：",this.selectedFaceId)
        cc.gg.httpUtil.httpPost("/user/profile/img/update",{imgId:this.selectedFaceId},function (result) {
            if (!result.succ) {
                cc.gg.toastMgr.showToast(LanguageMng.getSentence(150))
                return
            }

            this.completCount++
            cc.gg.dataMgr.getPlayerInfo().img = "face_"+this.selectedFaceId+".png"
            this.checkNetFinish()
        }.bind(this))
    },

    checkNetFinish:function () {
        if(this.netReqCount === this.completCount){
            this.node.destroy()
            cc.gg.toastMgr.showToast(LanguageMng.getSentence(149))
            this.uiMgr.updateLobbyUser()
            cc.gg.toastMgr.removeNetWaitting()
        }
    }
});
